<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="用户名/昵称">
          <el-input
            v-model="queryParams.keywords"
            placeholder="请输入用户名/昵称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="区域">
          <el-input
            v-model="queryParams.area"
            placeholder="请输入区域"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select
            v-model="queryParams.memberLevelId"
            placeholder="请选择会员等级"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="id" label="ID" prop="id" min-width="80" align="center" />
        <el-table-column key="familyName" label="家谱名称" prop="familyName" min-width="100" align="center" />
        <el-table-column key="username" label="用户名" prop="username" min-width="100" align="center" />
        <el-table-column key="nickname" label="昵称" prop="nickname" min-width="100" align="center" />
        <el-table-column key="mobile" label="手机号" prop="mobile" min-width="120" align="center" />
        <el-table-column key="levelName" label="等级名称" prop="levelName" min-width="120" align="center" />
        <el-table-column key="gender" label="性别" min-width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column key="email" label="邮箱" prop="email" min-width="160" align="center" />
        <el-table-column key="createTime" label="创建时间" prop="createTime" min-width="160" align="center" />
        <el-table-column key="mergerName" label="管理区域" prop="mergerName" min-width="200" align="center" />
        <el-table-column key="address" label="注册地址" prop="address" min-width="160" align="center" />
        <el-table-column key="account" label="钱包余额" prop="account" min-width="100" align="center" />
        <el-table-column
          v-if="areaCodeScope <= 6"
          key="price1"
          label="在世指标进货价"
          prop="price1"
          min-width="100"
          align="center"
        />
        <el-table-column
          v-if="areaCodeScope <= 6"
          key="price2"
          label="过世指标进货价"
          prop="price2"
          min-width="100"
          align="center"
        />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-dropdown>
              <el-button type="primary" size="small">
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleEdit(scope.row)" v-if=" scope.row.areaCodeScope > areaCodeScope  && scope.row.mergerName.includes(mergerName)  &&  hasAuth(['genealogy:member:edit'])">
                    <el-icon><Edit /></el-icon> 编辑
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="hasAuth(['genealogy:member:recharge_admin'])"
                    @click="handleRecharge(scope.row)">
                    <el-icon><Money /></el-icon> 充值
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="hasAuth(['genealogy:member:resetAll'])"
                    @click="handleResetPassword(scope.row)">
                    <el-icon><Key /></el-icon> 重置密码
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="hasAuth(['genealogy:member:embellish']) && (baseFlag === 1 || userFamilyId === scope.row.familyId) && scope.row.areaCodeScope >=7"
                    @click="handleSetEmbellisher(scope.row)">
                    <el-icon><UserFilled /></el-icon>
                    {{ scope.row.areaCodeScope == 7 ? '取消修谱人' : (scope.row.areaCodeScope == 8 ? '设为修谱人' : '') }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-if="scope.row.areaCodeScope<=6 && areaCodeScope<6 && scope.row.areaCodeScope > areaCodeScope && scope.row.mergerName.includes(mergerName)"
                    @click="handleSetPurchasePrice(scope.row)">
                    <el-icon><Money /></el-icon> 设置进货价
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <el-dialog v-model="editDialogVisible" title="编辑用户" width="500px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item label="性别">
          <Dict v-model="editForm.gender" code="gender" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="editForm.address" />
        </el-form-item>
        <el-form-item label="会员等级" >
          <el-select v-model="editForm.memberLevelId" placeholder="请选择会员等级">
            <el-option
              v-for="item in roleOptions.filter(opt => opt.sort > areaCodeScope)"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理区域" v-if="  currentMemberLevelSort < 6">
          <el-popover
            ref="areaPopoverRef"
            placement="bottom-start"
            :width="300"
            trigger="click"
            popper-class="custom-tree-select-popover"
          >
            <template #reference>
              <el-input
                v-model="selectedAreaName"
                placeholder="选择行政区划"
                readonly
                @click="() => {}"
                clearable
                @clear="clearAreaSelection"
              >
              </el-input>
            </template>
            <div class="tree-container">
              <el-tree
                ref="areaTreeRef"
                :data="regionOptions"
                node-key="areaCode"
                :props="{
                  isLeaf: (data) => isLeafNode(data),
                  label: 'name',
                  children: 'children',
                  level: 'level',
                  disabled: (data) => !isNodeSelectable(data)
                }"
                :load="loadRegionNodes"
                lazy
                @node-click="handleAreaNodeClick"
              />
            </div>
          </el-popover>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="rechargeDialogVisible" title="充值" width="400px">
      <el-form :model="rechargeForm" label-width="80px">
        <el-form-item label="充值类型">
          <el-select v-model="rechargeForm.type" placeholder="请选择充值类型">
            <el-option
              v-for="item in rechargeTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值数量">
          <el-input-number v-model="rechargeForm.amount" :min="1" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRecharge">充值</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="resetPasswordDialogVisible" title="重置密码" width="400px">
      <el-form :model="resetPasswordForm" label-width="80px" :rules="resetPasswordRules" ref="resetPasswordFormRef">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPasswordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPasswordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="embellisherDialogVisible" title="修改修谱人状态" width="400px">
      <el-form label-width="80px">
        <el-form-item label="确认信息">
          <div>{{ (embellisherForm.isEmbellisher || editForm.areaCodeScope === 7) ? '确认取消该用户的修谱人身份？' : '确认将该用户设置为修谱人？' }}</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="embellisherDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSetEmbellisher">确认</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="purchasePriceDialogVisible" title="设置进货价" width="400px">
      <el-form :model="purchasePriceForm" label-width="80px">
        <el-form-item label="商品">
          <el-select v-model="purchasePriceForm.packageId" placeholder="请选择商品" @change="handlePackageChange">
            <el-option
              v-for="item in packageOptions"
              :key="item.id"
              :label="item.packageName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格">
          <span class="price-display">{{ currentPackagePrice ? `¥${currentPackagePrice}` : '-' }}</span>
        </el-form-item>
        <el-form-item label="进货价">
          <el-input-number
            v-model="purchasePriceForm.price"
            :min="0"
            :max="currentPackagePrice || 999999"
            :precision="2"
            placeholder="请输入进货价"
            @change="handlePriceChange"
            :class="{ 'price-error': isPriceInvalid }"
          />
          <div class="price-tip" v-if="currentPackagePrice">
            <el-text type="warning" size="small">进货价不能超过商品价格 ¥{{ currentPackagePrice }}</el-text>
          </div>
          <div class="price-error-tip" v-if="isPriceInvalid">
            <el-text type="danger" size="small">进货价不能超过商品价格</el-text>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="purchasePriceDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="submitPurchasePrice"
          :disabled="isPriceInvalid || !purchasePriceForm.packageId || purchasePriceForm.price === null"
        >
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MemberLevelAPI from "@/api/genealogy/member-level.api";
import FamilyUserAPI from "@/api/genealogy/family-user.api";
import RegionAPI from "@/api/system/region.api";
import RechargeAPI from "@/api/genealogy/recharge.api";
import PackageAPI from "@/api/genealogy/package.api";
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Delete, Location, Edit, Money, Key, UserFilled, ArrowDown } from '@element-plus/icons-vue';
import { useUserStore } from "@/store";
import { hasAuth } from "@/plugins/permission";
const { areaCodeBelong, areaCodeScope,userFamilyId,baseFlag,mergerName } = useUserStore().userInfo;
console.log(areaCodeBelong,areaCodeScope,baseFlag)
const queryFormRef = ref();
const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keywords: '',
  area: '',
  memberLevelId: null
});

const pageData = ref([]);

const editDialogVisible = ref(false);
const editForm = reactive({
  id: undefined,
  nickname: '',
  mobile: '',
  gender: 1,
  email: '',
  address: '',
  areaCodeScope: 3,
  areaCodeBelong: null,
  memberLevelId: null
});

const regionOptions = ref([]);
const treeNodeMap = ref(new Map());
const roleOptions = ref([]);
const selectedAreaName = ref('');

// 获取当前选中会员等级的sort值
const currentMemberLevelSort = computed(() => {
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  return selectedLevel?.sort || 0;
});

const rechargeDialogVisible = ref(false);
const rechargeForm = reactive({
  userId: null,
  type: '', // 'deceased' 或 'alive'
  amount: 1
});
const rechargeTypes = [
  { label: '钱包余额', value: 'amount' }
];

const resetPasswordDialogVisible = ref(false);
const resetPasswordFormRef = ref();
const resetPasswordForm = reactive({
  userId: null,
  newPassword: '',
  confirmPassword: ''
});
const resetPasswordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const embellisherDialogVisible = ref(false);
const embellisherForm = reactive({
  userId: null,
  isEmbellisher: false
});

// 设置进货价相关
const purchasePriceDialogVisible = ref(false);
const purchasePriceForm = reactive({
  userId: null,
  packageId: null,
  price: null
});

const packageOptions = ref([]);
const currentPackagePrice = ref(null);
const isPriceInvalid = ref(false);

const areaPopoverRef = ref(null);

function handleQuery() {
  loading.value = true;
  FamilyUserAPI.getMembersPage(queryParams)
    .then((data: any) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleLevelQuery() {
  loading.value = true;
  const LevelParams = {
    pageNum: 1,
    pageSize: 100,
    memberLevelName: '',
    sort: areaCodeScope

  }
  MemberLevelAPI.getPage(LevelParams)
    .then((data: any) => {
      roleOptions.value = data.list.map(item => ({
        value: item.id,
        sort: item.sort,
        label: item.levelName
      }));
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value?.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

// 递归懒加载到目标节点
async function ensureAreaNodeLoaded(areaCode, tree, loadRegionNodes) {
  for (const node of tree) {
    if (node.areaCode === areaCode) {
      return node;
    }
    if (node.children === undefined && node.level < 4) {
      await new Promise(resolve => {
        loadRegionNodes(node, async (children) => {
          node.children = children;
          const found = await ensureAreaNodeLoaded(areaCode, children, loadRegionNodes);
          if (found) resolve(found);
          else resolve(null);
        });
      });
    } else if (node.children && node.children.length) {
      const found = await ensureAreaNodeLoaded(areaCode, node.children, loadRegionNodes);
      if (found) return found;
    }
  }
  return null;
}

function getAreaNameByCode(code, tree) {
  for (const node of tree) {
    if (node.areaCode === code) return node.name;
    if (node.children && node.children.length) {
      const found = getAreaNameByCode(code, node.children);
      if (found) return found;
    }
  }
  return '';
}

async function handleEdit(row) {
  // 先赋值表单
  Object.assign(editForm, row);

  // 先弹窗，提升用户体验
  editDialogVisible.value = true;

  // 递归懒加载到目标节点（areaCodeBelong）
  if (row.areaCodeBelong) {
    await ensureAreaNodeLoaded(row.areaCodeBelong, regionOptions.value, loadRegionNodes);
    // 回显名称
    if (row.mergerName) {
      selectedAreaName.value = row.mergerName;
    } else {
      selectedAreaName.value = getAreaNameByCode(row.areaCodeBelong, regionOptions.value);
    }
  } else {
    selectedAreaName.value = '';
  }
}

function submitEdit() {
  if (!editForm.id) {
    ElMessage.error('缺少用户ID，无法编辑');
    return;
  }
  loading.value = true;
  const submitData = {
    id: editForm.id,
    username: editForm.username,
    nickname: editForm.nickname,
    mobile: editForm.mobile,
    gender: editForm.gender,
    email: editForm.email,
    address: editForm.address,
    roleIds: [editForm.memberLevelId],
    memberLevelId: editForm.memberLevelId,
    areaCodeBelong: editForm.areaCodeBelong,
    areaCodeScope: editForm.areaCodeScope,
  };
  FamilyUserAPI.edit(editForm.id, submitData)
    .then(() => {
      ElMessage.success('编辑成功');
      editDialogVisible.value = false;
      selectedAreaName.value = '';
      handleQuery();
    })
    .catch(() => {
      ElMessage.error('编辑失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

function loadRegionNodes(node, resolve) {
  if (node.level === 0) {
    return resolve(regionOptions.value);
  }

  // 获取当前选中会员等级
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  if (!selectedLevel) return resolve([]);

  // 如果当前节点级别已经等于或超过会员等级的sort值，则不再加载子节点
  if (node.level >= selectedLevel.sort) {
    return resolve([]);
  }

  const areaCode = node.data.areaCode;
  if (areaCode) {
    RegionAPI.getOptions({areaCode})
      .then(data => {
        data.forEach(item => {
          treeNodeMap.value.set(item.areaCode, item);
        });
        resolve(data);
      })
      .catch(() => {
        resolve([]);
      });
  }else{
    const  areaCode = node.areaCode;
    RegionAPI.getOptions({areaCode})
      .then(data => {
        data.forEach(item => {
          treeNodeMap.value.set(item.areaCode, item);
        });
        resolve(data);
      })
      .catch(() => {
        resolve([]);
      });
  }
}

function handleAreaNodeClick(data, node) {
  // 获取当前选中会员等级
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  if (!selectedLevel) return;

  // 只有当节点级别与会员等级的sort值相匹配时才允许选择
  if (data.level === selectedLevel.sort) {
    editForm.areaCodeBelong = data.areaCode;
    let currentNode = node;
    let pathNames = [];
    while (currentNode && currentNode.level > 0) {
      pathNames.unshift(currentNode.label);
      currentNode = currentNode.parent;
    }
    selectedAreaName.value = pathNames.join(" - ");

    // 使用正确的ref关闭popover
    if (areaPopoverRef.value) {
      areaPopoverRef.value.hide();
    }
  }
}

function clearAreaSelection() {
  editForm.areaCodeBelong = null;
  selectedAreaName.value = "";
}

// 恢复原有函数
function handSelectLevel(data) {
  if (!data) return;

  // 直接从映射中获取节点数据
  const selectedNode = treeNodeMap.value.get(data);
  if (!selectedNode) {
    console.error('未能找到选中节点信息:', data);
    return;
  }

  // 获取当前选中会员等级的sort值
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  if (!selectedLevel) return;

  // 根据会员等级判断最大可选层级
  if (selectedNode.level !== selectedLevel.sort) {
    ElMessage.warning(`当前会员等级只能选择${getLevelName(selectedLevel.sort)}级别的区域`);
    editForm.areaCodeBelong = null;
    selectedAreaName.value = "";
    return;
  }
}

// 获取层级名称
function getLevelName(level) {
  const levelMap = {
    1: '省',
    2: '市',
    3: '县',
    4: '镇',
    5: '村'
  };
  return levelMap[level] || '未知';
}

// 判断节点是否可选
function isNodeSelectable(node) {
  if (!node) return false;

  // 获取当前选中会员等级
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  if (!selectedLevel) return false;

  // 如果节点级别等于会员等级的sort值，则可选
  // 如果节点级别小于会员等级的sort值，则可展开但不可选
  // 如果节点级别大于会员等级的sort值，则不可选
  if (node.level < selectedLevel.sort) {
    // 小于当前等级的节点可以展开但不可选
    return false;
  } else if (node.level === selectedLevel.sort) {
    // 等于当前等级的节点可选
    return true;
  } else {
    // 大于当前等级的节点不可选
    return false;
  }
}

// 判断节点是否为叶子节点
function isLeafNode(data) {
  if (!data) return false;

  // 获取当前选中会员等级
  const selectedLevel = roleOptions.value.find(item => item.value === editForm.memberLevelId);
  if (!selectedLevel) return false;

  // 如果节点级别等于会员等级的sort值，则为叶子节点
  return data.level === selectedLevel.sort;
}

// 监听会员等级选择变化
watch(() => editForm.memberLevelId, (newValue) => {
  if (newValue) {
    const selectedLevel = roleOptions.value.find(item => item.value === newValue);
    if (selectedLevel) {
      // 重置区域选择
      editForm.areaCodeBelong = null;
      selectedAreaName.value = '';

      // 清空区域选项并重新加载
      regionOptions.value = [];
      treeNodeMap.value.clear();

      // 重新加载根据会员等级对应的区域级别
      if (selectedLevel.sort <= 5) {
        // 重新加载省级区域
        RegionAPI.getOptions({ areaCode: areaCodeBelong }).then((data) => {
          regionOptions.value = data;
          data.forEach(item => {
            treeNodeMap.value.set(item.areaCode, item);
          });
        });
      }

      // 如果是不需要选择区域的等级，直接清空
      if (selectedLevel.sort > 5) {
        editForm.areaCodeBelong = null;
        selectedAreaName.value = '';
      }
    }
  } else {
    // 如果清空了会员等级，也清空区域选择
    editForm.areaCodeBelong = null;
    selectedAreaName.value = '';
    regionOptions.value = [];
    treeNodeMap.value.clear();
  }
});

function handleRecharge(row) {
  rechargeForm.userId = row.id;
  rechargeForm.type = '';
  rechargeForm.amount = 1;
  rechargeDialogVisible.value = true;
}

function submitRecharge() {
  if (!rechargeForm.type || !rechargeForm.amount) {
    ElMessage.error('请选择充值类型并填写数量');
    return;
  }
  RechargeAPI.inUsercreaseAmount({
    userId: rechargeForm.userId,
    money: rechargeForm.amount,
    operationType: 3
  }).then(() => {
    ElMessage.success('充值成功');
    rechargeDialogVisible.value = false;
    handleQuery();
  }).catch(() => {
    ElMessage.error('充值失败');
  });
}

function handleResetPassword(row) {
  resetPasswordForm.userId = row.id;
  resetPasswordForm.newPassword = '';
  resetPasswordForm.confirmPassword = '';
  resetPasswordDialogVisible.value = true;
}

function submitResetPassword() {
  resetPasswordFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      FamilyUserAPI.resetPassword(resetPasswordForm.userId, {
        password: resetPasswordForm.newPassword
      })
        .then(() => {
          ElMessage.success('密码重置成功');
          resetPasswordDialogVisible.value = false;
        })
        .catch(() => {
          ElMessage.error('密码重置失败');
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
}

function handleSetEmbellisher(row) {
  embellisherForm.userId = row.id;
  embellisherForm.isEmbellisher = row.isEmbellisher || row.areaCodeScope === 7 || false;
  embellisherDialogVisible.value = true;
}

function submitSetEmbellisher() {
  if (!embellisherForm.userId) {
    ElMessage.error('缺少用户ID，无法修改修谱人状态');
    return;
  }
  loading.value = true;

  FamilyUserAPI.setEmbellisher({
    userId: embellisherForm.userId,
    isEmbellisher: !embellisherForm.isEmbellisher
  })
    .then(() => {
      ElMessage.success(embellisherForm.isEmbellisher ? '取消修谱人成功' : '设置修谱人成功');
      embellisherDialogVisible.value = false;
      handleQuery();
    })
    .catch(() => {
      ElMessage.error(embellisherForm.isEmbellisher ? '取消修谱人失败' : '设置修谱人失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleSetPurchasePrice(row) {
  purchasePriceForm.userId = row.id;
  purchasePriceForm.packageId = null;
  purchasePriceForm.price = null;
  currentPackagePrice.value = null;
  isPriceInvalid.value = false;
  purchasePriceDialogVisible.value = true;
}

function handlePackageChange() {
  if (purchasePriceForm.packageId) {
    // 获取商品价格
    const selectedPackage = packageOptions.value.find(pkg => pkg.id === purchasePriceForm.packageId);
    if (selectedPackage) {
      currentPackagePrice.value = selectedPackage.price;
    }

    // 获取用户当前进货价
    if (purchasePriceForm.userId && purchasePriceForm.packageId) {
      FamilyUserAPI.getPurchasePrice(purchasePriceForm.userId, purchasePriceForm.packageId)
        .then((data: any) => {
          if (data && data.price !== undefined) {
            purchasePriceForm.price = data.price;
            // 检查价格是否有效
            handlePriceChange();
          } else {
            purchasePriceForm.price = null;
            isPriceInvalid.value = false;
          }
        })
        .catch(() => {
          purchasePriceForm.price = null;
          isPriceInvalid.value = false;
        });
    }
  } else {
    currentPackagePrice.value = null;
    purchasePriceForm.price = null;
    isPriceInvalid.value = false;
  }
}

function handlePriceChange() {
  if (purchasePriceForm.price !== null && currentPackagePrice.value !== null) {
    if (purchasePriceForm.price > currentPackagePrice.value) {
      isPriceInvalid.value = true;
    } else {
      isPriceInvalid.value = false;
    }
  } else {
    isPriceInvalid.value = false;
  }
}

function submitPurchasePrice() {
  // 验证商品选择
  if (!purchasePriceForm.packageId) {
    ElMessage.error('请选择商品');
    return;
  }

  // 验证进货价输入
  if (purchasePriceForm.price === null || purchasePriceForm.price === undefined) {
    ElMessage.error('请输入进货价');
    return;
  }

  if (purchasePriceForm.price < 0) {
    ElMessage.error('进货价不能为负数');
    return;
  }

  // 验证进货价不能超过商品价格
  if (currentPackagePrice.value !== null && purchasePriceForm.price > currentPackagePrice.value) {
    ElMessage.error(`进货价 ¥${purchasePriceForm.price} 不能超过商品价格 ¥${currentPackagePrice.value}`);
    return;
  }

  // 验证进货价不能等于商品价格（可选，根据业务需求决定）
  if (currentPackagePrice.value !== null && purchasePriceForm.price === currentPackagePrice.value) {
    ElMessage.warning('进货价等于商品价格，请确认是否合理');
  }

  loading.value = true;

  FamilyUserAPI.setPurchasePrice({
    userId: purchasePriceForm.userId,
    packageId: purchasePriceForm.packageId,
    price: purchasePriceForm.price
  })
    .then(() => {
      ElMessage.success('设置进货价成功');
      purchasePriceDialogVisible.value = false;
      // 重置表单
      purchasePriceForm.packageId = null;
      purchasePriceForm.price = null;
      currentPackagePrice.value = null;
      handleQuery();
    })
    .catch(() => {
      ElMessage.error('设置进货价失败');
    })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  handleQuery();
  handleLevelQuery();
  // 初始化加载省级区域
  // RegionAPI.getOptions({ areaCode: areaCodeBelong }).then((data) => {
  //   regionOptions.value = data;
  //   data.forEach(item => {
  //     treeNodeMap.value.set(item.areaCode, item);
  //   });
  // });
  // 加载商品列表
  PackageAPI.getPage1({ pageNum: 1, pageSize: 100 }).then(res => {
    packageOptions.value = res.list || [];
  });
});
</script>

<style scoped>
.tree-container {
  max-height: 300px;
  overflow-y: auto;
}

.custom-tree-select-popover {
  padding: 8px;
}

.price-display {
  font-weight: bold;
  color: #409eff;
}

.price-tip {
  margin-top: 5px;
}

.price-error-tip {
  margin-top: 5px;
}

.price-error .el-input-number__decrease,
.price-error .el-input-number__increase,
.price-error .el-input__inner {
  border-color: #f56c6c;
}

.price-error .el-input-number__decrease:hover,
.price-error .el-input-number__increase:hover {
  border-color: #f56c6c;
}
</style>
